package user

import (
	"errors"
	"gorm.io/gorm"
	"shejiao/base"
	"shejiao/common/model/user"
	"time"
)

var UserService = userService{orm: base.Mysql}

type userService struct {
	orm *gorm.DB
}

func (*userService) Info(userId int64) user.UserInfo {
	var ui user.UserInfo
	base.Mysql.Find(&ui, "user_id = ?", userId)
	return ui
}

func (s *userService) Match(id int64, matchType string, region string) (int64, error) {
	// mysql 搜索一个在线的用户
	var users user.UserInfo
	pingAt := time.Now().Add(-10 * time.Second)
	where := `
		region = ? and ping_at > ? and user_id not in (select match_id from user_match_user where user_id = ?)
	`
	base.Mysql.Model(user.UserInfo{}).Where(where, region, pingAt, id).Find(&users)

	if users.Id == 0 {
		// 没有匹配到
		return 0, errors.New("没有匹配到")
	}

	// 创建匹配记录
	match := user.UserMatchUser{UserId: id, MatchId: users.UserId, MatchType: matchType, CreateAt: time.Now().Unix()}
	base.Mysql.Create(&match)

	return users.Id, nil
}
